<template>
  <div class="enterprise-detail-page">
    <!-- 顶部导航栏 -->
    <div class="detail-header">
      <div class="header-left">
        <div class="back-btn" @click="$router.go(-1)">
          <i class="el-icon-arrow-left"></i>
        </div>
        <div class="header-info">
          <div class="header-title-row">
            <h1>{{ enterprise.name || '加载中...' }}</h1>
            <el-tag :type="enterprise.status === 1 ? 'success' : 'danger'" size="small" effect="dark">
              {{ enterprise.status === 1 ? '正常运营' : '已禁用' }}
            </el-tag>
          </div>
          <div class="header-subtitle">
            <span>ID: {{ enterprise.id }}</span>
            <el-divider direction="vertical"></el-divider>
            <span>统一社会信用代码: {{ enterprise.creditCode || '未填写' }}</span>
          </div>
        </div>
      </div>
      <div class="header-right">
        <el-button type="primary" icon="el-icon-edit" @click="showEditDialog">编辑企业信息</el-button>
      </div>
    </div>

    <!-- 概览统计卡片 (复用Dashboard风格) -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <div class="stat-card stat-card-primary">
          <div class="stat-icon">
            <i class="el-icon-money"></i>
          </div>
          <div class="stat-content">
            <div class="stat-label">总收入</div>
            <div class="stat-value">¥{{ formatMoney(statistics.total_revenue) }}</div>
            <div class="stat-sub">累计交易额</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card stat-card-success">
          <div class="stat-icon">
            <i class="el-icon-user"></i>
          </div>
          <div class="stat-content">
            <div class="stat-label">用户规模</div>
            <div class="stat-value">{{ statistics.user_count || 0 }} <span class="unit">/ {{ enterprise.maxUsers }}</span></div>
            <div class="stat-sub">活跃用户数</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card stat-card-warning">
          <div class="stat-icon">
            <i class="el-icon-s-order"></i>
          </div>
          <div class="stat-content">
            <div class="stat-label">订单总量</div>
            <div class="stat-value">{{ statistics.order_count || 0 }}</div>
            <div class="stat-sub">累计支付订单</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card stat-card-danger">
          <div class="stat-icon">
            <i class="el-icon-trophy"></i>
          </div>
          <div class="stat-content">
            <div class="stat-label">订阅方案</div>
            <div class="stat-value-text">{{ getPlanName(enterprise.subscriptionPlan) }}</div>
            <div class="stat-sub">有效期至: 永久</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 主要内容 Tabs -->
    <div class="main-content-card">
      <el-tabs v-model="activeTab" class="custom-tabs">
        
        <!-- 用户管理 -->
        <el-tab-pane name="users">
          <span slot="label"><i class="el-icon-user"></i> 用户管理</span>
          <el-table :data="users" v-loading="loadingUsers" stripe style="width: 100%" class="mt-table">
            <el-table-column prop="username" label="用户信息" min-width="200">
              <template slot-scope="scope">
                <div class="user-cell">
                  <el-avatar :size="36" icon="el-icon-user-solid" class="user-avatar"></el-avatar>
                  <div class="user-info">
                    <div class="name">{{ scope.row.username }}</div>
                    <div class="real-name">{{ scope.row.email || '未填写邮箱' }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="系统角色" width="150">
              <template slot-scope="scope">
                 <el-tag v-if="scope.row.is_enterprise_admin" type="warning" size="small" effect="plain">企业管理员</el-tag>
                 <el-tag v-else size="small" type="info" effect="plain">{{ scope.row.roles || '普通员工' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号" width="150" />
            <el-table-column label="账号状态" width="100">
              <template slot-scope="scope">
                <div class="status-dot" :class="scope.row.status === 1 ? 'online' : 'offline'">
                  {{ scope.row.status === 1 ? '正常' : '禁用' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="注册时间" width="180">
              <template slot-scope="scope">{{ formatDate(scope.row.created_at) }}</template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 订单记录 -->
        <el-tab-pane name="orders">
          <span slot="label"><i class="el-icon-s-order"></i> 订单记录</span>
          <el-table :data="orders" v-loading="loadingOrders" stripe style="width: 100%" class="mt-table">
            <el-table-column prop="out_trade_no" label="订单号" width="220">
              <template slot-scope="scope">
                <span class="font-mono">{{ scope.row.out_trade_no }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="product_name" label="商品名称" min-width="200" />
            <el-table-column label="支付金额" width="150">
              <template slot-scope="scope">
                <span class="money-text">¥{{ formatMoney(scope.row.amount) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="120">
              <template slot-scope="scope">
                <el-tag :type="getOrderStatusType(scope.row.status)" size="small" effect="dark">
                  {{ getOrderStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="交易时间" width="180">
              <template slot-scope="scope">{{ formatDate(scope.row.created_at) }}</template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 融资申请 -->
        <el-tab-pane name="financing">
          <span slot="label"><i class="el-icon-money"></i> 融资申请</span>
          <el-table :data="financingRequests" v-loading="loadingFinancing" stripe style="width: 100%" class="mt-table">
            <el-table-column prop="id" label="申请ID" width="100" />
            <el-table-column label="申请金额" width="180">
              <template slot-scope="scope">
                <span class="money-text large">¥{{ formatMoney(scope.row.requested_amount) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="purpose" label="资金用途" min-width="200" />
            <el-table-column label="AI评估" width="120">
              <template slot-scope="scope">
                <div class="score-badge" :class="getScoreClass(scope.row.score)">
                  {{ scope.row.score ? scope.row.score + '分' : '未评估' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="当前进度" width="120">
              <template slot-scope="scope">
                <el-tag :type="getFinancingStatusType(scope.row.status)" size="small">
                  {{ getFinancingStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="申请时间" width="180">
              <template slot-scope="scope">{{ formatDate(scope.row.created_at) }}</template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <!-- 操作日志 -->
        <el-tab-pane name="logs">
          <span slot="label"><i class="el-icon-document"></i> 操作日志</span>
          <div class="log-container">
            <el-timeline>
              <el-timeline-item
                v-for="(log, index) in logs"
                :key="index"
                :timestamp="formatDate(log.created_at)"
                :color="'#0bbd87'"
                placement="top">
                <el-card class="log-card" shadow="hover">
                  <h4>{{ log.action }}</h4>
                  <p class="log-detail">{{ log.detail }}</p>
                </el-card>
              </el-timeline-item>
            </el-timeline>
            <div v-if="logs.length === 0" class="empty-logs">暂无操作日志</div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 编辑企业对话框 -->
    <el-dialog title="编辑企业信息" :visible.sync="dialogVisible" width="500px" custom-class="mt-dialog">
        <div style="text-align: center; padding: 20px; color: #666;">
           <i class="el-icon-info" style="font-size: 40px; color: #FFD100; margin-bottom: 10px;"></i>
           <p>编辑功能请返回列表页操作</p>
        </div>
        <div slot="footer">
          <el-button type="primary" @click="dialogVisible = false">知道了</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import http from '@/api/http'

export default {
  name: 'SuperAdminEnterpriseDetail',
  data() {
    return {
      enterpriseId: this.$route.params.id,
      enterprise: {},
      statistics: {},
      logs: [],
      users: [],
      orders: [],
      financingRequests: [],
      activeTab: 'users',
      dialogVisible: false,
      loadingUsers: false,
      loadingOrders: false,
      loadingFinancing: false
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    async loadData() {
      try {
        // 1. 获取企业基本信息和统计
        const { data: detailData } = await http.get(`/super-admin/enterprises/${this.enterpriseId}`)
        if (detailData.code === 0) {
          this.enterprise = detailData.data.enterprise
          this.statistics = detailData.data.statistics
          this.logs = detailData.data.logs || []
        }

        // 2. 获取用户列表
        this.loadingUsers = true
        try {
          const { data: userData } = await http.get(`/super-admin/enterprises/${this.enterpriseId}/users`)
          if (userData.code === 0) this.users = userData.data
        } finally { this.loadingUsers = false }

        // 3. 获取订单
        this.loadingOrders = true
        try {
          const { data: orderData } = await http.get(`/super-admin/enterprises/${this.enterpriseId}/orders`)
          if (orderData.code === 0) this.orders = orderData.data
        } finally { this.loadingOrders = false }

        // 4. 获取融资
        this.loadingFinancing = true
        try {
          const { data: financingData } = await http.get(`/super-admin/enterprises/${this.enterpriseId}/financing`)
          if (financingData.code === 0) this.financingRequests = financingData.data
        } finally { this.loadingFinancing = false }

      } catch (error) {
        console.error('Load enterprise detail error:', error)
        this.$message.error('加载数据失败')
      }
    },
    showEditDialog() {
      this.dialogVisible = true
    },
    formatMoney(value) {
      if (!value) return '0.00'
      return Number(value).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
    },
    formatDate(dateStr) {
      if (!dateStr) return '-'
      return new Date(dateStr).toLocaleString('zh-CN')
    },
    getPlanName(plan) {
      const names = { FREE: '免费版', BASIC: '基础版', PRO: '专业版', ENTERPRISE: '企业版' }
      return names[plan] || plan
    },
    getOrderStatusType(status) {
      const map = { PENDING: 'warning', SUCCESS: 'success', FAILED: 'danger', CLOSED: 'info' }
      return map[status] || 'info'
    },
    getOrderStatusText(status) {
      const map = { PENDING: '待支付', SUCCESS: '支付成功', FAILED: '支付失败', CLOSED: '已关闭' }
      return map[status] || status
    },
    getFinancingStatusType(status) {
        const map = { 
            DRAFT: 'info', SUBMITTED: 'primary', EVALUATED: 'warning', 
            APPROVED: 'success', REJECTED: 'danger', DISBURSED: 'success' 
        }
        return map[status] || 'info'
    },
    getFinancingStatusText(status) {
        const map = { 
            DRAFT: '草稿', SUBMITTED: '已提交', EVALUATED: '已评估', 
            APPROVED: '审批通过', REJECTED: '已拒绝', DISBURSED: '已放款' 
        }
        return map[status] || status
    },
    getScoreClass(score) {
        if (!score) return 'score-none'
        if (score >= 80) return 'score-high'
        if (score >= 60) return 'score-mid'
        return 'score-low'
    }
  }
}
</script>

<style scoped>
.enterprise-detail-page {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 头部样式优化 */
.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}

.header-left {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.back-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 4px;
}

.back-btn:hover {
  background: #e6e8eb;
  color: var(--primary-color);
}

.header-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.header-title-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-title-row h1 {
  margin: 0;
  font-size: 22px;
  font-weight: 700;
  color: var(--text-primary);
}

.header-subtitle {
  font-size: 13px;
  color: var(--text-tertiary);
  display: flex;
  align-items: center;
}

/* 统计卡片 - 复用Dashboard样式 */
.stats-row {
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  border: 1px solid transparent;
  height: 120px;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
}

.stat-card-primary .stat-icon { background: #fff9e6; color: #FFD100; }
.stat-card-success .stat-icon { background: #e6f9f0; color: #06C05F; }
.stat-card-warning .stat-icon { background: #fff3e0; color: #ff9800; }
.stat-card-danger .stat-icon { background: #ffebee; color: #ff5757; }

.stat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 8px;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: var(--text-primary);
  font-family: 'DIN Alternate', sans-serif;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-value-text {
  font-size: 22px;
  font-weight: 700;
  color: var(--text-primary);
  line-height: 1;
  margin-bottom: 4px;
}

.stat-sub {
  font-size: 12px;
  color: var(--text-tertiary);
}

.unit {
  font-size: 16px;
  color: var(--text-tertiary);
  font-weight: normal;
}

/* 内容区域 */
.main-content-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
  min-height: 500px;
}

/* 表格样式增强 */
.user-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  background: var(--primary-gradient);
  flex-shrink: 0;
}

.user-info {
  display: flex;
  flex-direction: column;
}

.user-info .name {
  font-weight: 600;
  color: var(--text-primary);
}

.user-info .real-name {
  font-size: 12px;
  color: var(--text-tertiary);
}

.status-dot {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
}

.status-dot::before {
  content: '';
  display: block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.status-dot.online::before { background: #06C05F; }
.status-dot.offline::before { background: #ff4949; }

.font-mono {
  font-family: Monaco, Menlo, Consolas, monospace;
  color: var(--text-regular);
}

.money-text {
  font-family: 'DIN Alternate', sans-serif;
  font-weight: 600;
}

.money-text.large {
  font-size: 16px;
  color: #ff9800;
}

.score-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: bold;
  font-size: 13px;
}

.score-high { color: #06C05F; background: rgba(6, 192, 95, 0.1); }
.score-mid { color: #ff9800; background: rgba(255, 152, 0, 0.1); }
.score-low { color: #ff5757; background: rgba(255, 87, 87, 0.1); }
.score-none { color: #909399; background: #f4f4f5; }

/* 日志样式 */
.log-container {
  padding: 20px;
}

.log-card {
  border: none;
  background: #f9fafc;
}

.log-card h4 {
  margin: 0 0 8px;
  font-size: 15px;
  color: #2c3e50;
}

.log-detail {
  margin: 0;
  color: #666;
  font-size: 13px;
  line-height: 1.5;
}

.empty-logs {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}
</style>
